package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
)

type Response struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Version string `json:"version"`
}

// 取得客户端IP
func getClientIp(req *http.Request) string {
	remoteAddr := req.RemoteAddr
	if ip := req.Header.Get("Remote_addr"); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}
	return remoteAddr
}

// HTTP server健康检查
func healthz(w http.ResponseWriter, r *http.Request) {

	// 1. 接收客户端 request，并将 request 中带的 header 写入 response header
	fmt.Println("Header参数列表：", r.Header)
	if len(r.Header) > 0 {
		for k,v := range r.Header {
			fmt.Printf("%s=%s\n", k, v[0])
			w.Header().Set(k, v[0])
		}
	}
	fmt.Println("Header参数列表(写入后)：", r.Header)

	// 2. 读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	version := os.Getenv("GOPATH")
	w.Header().Set("version", version)

	// 3. Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
	ip := r.Header.Get("X-Real-IP")
	fmt.Println("Source IP is: ", ip)

	// 4. 当访问 localhost/healthz 时，应返回 200
	returnCode := 200
	resp := Response{returnCode, "Success", version}
	err := json.NewEncoder(w).Encode(resp)
	if err != nil {
		fmt.Printf("Error: %s \n", err)
	}
	fmt.Printf("Host IP is %s, returnCode is %d \n", getClientIp(r), returnCode)
}

func main() {
	http.HandleFunc("/healthz", healthz)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
